package uestc.lj.basicPromotion.manacher;

/**
 * Manacher算法解决最长回文子串
 *
 * @Author:Crazlee
 * @Date:2021/11/26
 */
public class Code01_Manacher {
	/**
	 * 求最长回文子串
	 *
	 * @param s 串
	 * @return 最长回文子串的长度
	 */
	public static int maxLcpsLength(String s) {
		if (s == null || s.length() == 0) {
			return 0;
		}
		char[] str = manacherString(s);
		// 1.回文半径数组
		int[] pArr = new int[str.length];
		//中心点索引
		int C = -1;
		//回文右边界的再往右一个位置，最右的有效区是R-1位置
		int R = -1;
		//扩出来的最大值
		int max = Integer.MIN_VALUE;

		for (int i = 0; i != str.length; i++) {

			pArr[i] = R > i ? Math.min(pArr[2 * C - i], R - i) : 1;

			while (i + pArr[i] < str.length && i - pArr[i] > -1) {
				if (str[i + pArr[i]] == str[i - pArr[i]]) {
					pArr[i]++;
				} else {
					break;
				}
			}
			if (i + pArr[i] > R) {
				R = i + pArr[i];
				C = i;
			}
			max = Math.max(max, pArr[i]);
		}
		return max - 1;
	}

	/**
	 * 处理字符串，添加无效字符
	 *
	 * @param s 字符串
	 * @return 每两个字符之中添加无效字符后的字符数组
	 */
	private static char[] manacherString(String s) {
		char[] charArray = s.toCharArray();
		char[] chars = new char[charArray.length * 2 + 1];
		int index = 0;
		for (int i = 0; i < chars.length; i++) {
			chars[i] = (i & 1) == 0 ? '#' : charArray[index++];
		}
		return chars;
	}
}